//
//  PedometerViewController.swift
//  elarc01
//
//  Created by elarc on 2017/2/17.
//  Copyright © 2017年 elarc. All rights reserved.
//

import UIKit
import CoreMotion

class PedometerViewController: UIViewController {
    
    let pedometer = CMPedometer()
    var textView = UITextView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        textView = UITextView()
        textView.backgroundColor = UIColor.purpleColor()
        textView.frame = CGRectMake(20, 100, UIScreen.mainScreen().bounds.size.width - 40, UIScreen.mainScreen().bounds.size.height - 100)
        self.view.addSubview(textView)
        startPedometerUpdates()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func startPedometerUpdates() {
        
        guard CMPedometer.isStepCountingAvailable() else {
            self.textView.text = "\n当前设备不支持获取步数\n"
            return
        }
        
        
        let cal = NSCalendar.currentCalendar()
        let comps = cal.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: NSDate())
        comps.hour = 0
        comps.minute = 0
        comps.second = 0
        let midnightOfToday = cal.dateFromComponents(comps)
        
        self.pedometer.startPedometerUpdatesFromDate(midnightOfToday!) { (pedometerData, error) in
            
            guard error == nil else {
                print(error!)
                return
            }
            var text = "---今日运动数据---\n"
            if let numberOfSteps = pedometerData?.numberOfSteps {
                text += "步数: \(numberOfSteps)\n"
            }
            if let distance = pedometerData?.distance {
                text += "距离: \(distance)\n"
            }
            if let floorsAscended = pedometerData?.floorsAscended {
                text += "上楼: \(floorsAscended)\n"
            }
            if let floorsDescended = pedometerData?.floorsDescended {
                text += "下楼: \(floorsDescended)\n"
            }
            if #available(iOS 9.0, *) {
                if let currentPace = pedometerData?.currentPace {
                    text += "速度: \(currentPace)m/s\n"
                }
            } else {
                // Fallback on earlier versions
            }
            if #available(iOS 9.0, *) {
                if let currentCadence = pedometerData?.currentCadence {
                    text += "速度: \(currentCadence)步/秒\n"
                }
            } else {
                // Fallback on earlier versions
            }
            
            dispatch_async(dispatch_get_main_queue(), {
                self.textView.text = text
            })
        }
    }
    
}
